import type { QueryKey } from '@tanstack/query-core';
import type { IDraft } from '@/interfaces';
import { type Dispatch, type SetStateAction, useContext } from 'react';
import useToast from '@/hooks/useToast';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { usePathname } from 'next/navigation';
import { queryDraft, removeDraft } from '@/services/api';
import Link from 'next/link';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import ContentHtml from '@/app/[locale]/common/content/html';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import { PostEditContext } from '@/contexts/post-edit';

export type TViewDraftTranslatedField =
  | 'name'
  | 'overview'
  | 'delete'
  | 'restore'
  | 'deleteCompleted'
  | 'content';

export default function ViewDraft({
  queryKey,
  currentItem,
  setCurrentItem,
  translatedFields = {
    name: '标题',
    overview: '概述',
    content: '内容',
    delete: '删除',
    restore: '恢复',
    deleteCompleted: '删除完成',
  },
}: {
  queryKey: QueryKey;
  currentItem: IDraft;
  setCurrentItem: Dispatch<SetStateAction<IDraft | undefined>>;
  translatedFields?: Record<TViewDraftTranslatedField, any>;
}) {
  const { onNavItemName } = useContext(PostEditContext);
  const { show } = useToast();
  const queryClient = useQueryClient();
  const pathname = usePathname();

  const queryDraftQuery = useQuery(
    ['/forum', '/drafts', currentItem.id],
    async (context) => {
      return (await queryDraft({
        id: context.queryKey[2] + '',
      })) as IDraft;
    },
  );

  const removeDraftMutation = useMutation(removeDraft);

  async function onClickDelete() {
    try {
      await removeDraftMutation.mutateAsync({
        id: currentItem.id + '',
      });

      await queryClient.refetchQueries({ queryKey }, { throwOnError: true });
      setCurrentItem(undefined);

      show({
        type: 'SUCCESS',
        message: translatedFields.deleteCompleted,
      });
    } catch (e) {
      removeDraftMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onClickRestore() {
    onNavItemName('编辑');
  }

  if (queryDraftQuery.data) {
    const data = queryDraftQuery.data;

    return (
      <div className="vstack gap-4 overflow-hidden">
        <div className="hstack flex-wrap align-items-center gap-2">
          <button
            disabled={removeDraftMutation.isLoading}
            className="btn btn-danger"
            onClick={onClickDelete}
          >
            {removeDraftMutation.isLoading ? (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            ) : (
              <i className="bi bi-trash me-2"></i>
            )}
            {translatedFields.delete}
          </button>
          <Link
            onClick={onClickRestore}
            className="btn btn-primary"
            href={pathname.replace('/draft', `?draft=${data.id}`)}
          >
            <i className="bi bi-box-arrow-in-left me-2"></i>
            {translatedFields.restore}
          </Link>
        </div>

        <div className="card">
          <div className="card-header">{translatedFields.name}</div>
          <div className="card-body">{data.name ? data.name : <Nodata />}</div>
        </div>

        <div className="card">
          <div className="card-header">{translatedFields.overview}</div>
          <div className="card-body">
            {data.overview ? (
              <ContentHtml content={data.overview} />
            ) : (
              <Nodata />
            )}
          </div>
        </div>

        <div className="card">
          <div className="card-header">{translatedFields.content}</div>
          <div className="card-body">
            {data.content ? <ContentHtml content={data.content} /> : <Nodata />}
          </div>
        </div>
      </div>
    );
  }

  if (queryDraftQuery.error) {
    return <Alert type="error" message={queryDraftQuery.error} />;
  }

  return <AlertLoad />;
}
